<template>
    <div class="yemian">
        <div class="bigbox">
            <div class="title">找回密码</div>

            <!-- 步骤指示器 -->
            <div class="steps">
                <div :class="['step', step === 1 ? 'active' : 'completed']">1. 验证手机号</div>
                <div :class="['step', step === 2 ? 'active' : step > 2 ? 'completed' : '']">2. 验证邮箱</div>
                <div :class="['step', step === 3 ? 'active' : '']">3. 重置密码</div>
            </div>

            <!-- 第一步：验证手机号 -->
            <div v-if="step === 1">
                <div class="content">
                    <img :src="require('@/assets/name.png')" alt="phone" class="imge">
                    <input type="text" placeholder="请输入手机号" class="input" v-model="phone" maxlength="11" />
                </div>
                <button class="login-btn" @click="checkPhone">下一步</button>
            </div>

            <!-- 第二步：验证邮箱（如果需要更新邮箱则显示输入框） -->
            <div v-if="step === 2">
                <div class="content">
                    <img :src="require('@/assets/imag2.png')" alt="youxiang" class="imge">
                    <input type="text" placeholder="请输入邮箱" class="input" v-model="email" :disabled="!needUpdateEmail" />
                </div>

                <div v-if="needUpdateEmail" class="hint">该账号未绑定邮箱，请设置邮箱用于接收验证码</div>

                <div class="content">
                    <img :src="require('@/assets/yanzhengma.png')" alt="yanzhengma" class="imge">
                    <input type="text" placeholder="请输入验证码" class="input" v-model="verificationCode" />
                    <button class="send-code-btn" @click="sendCode" :disabled="countdown > 0">
                        {{ countdown > 0 ? `${countdown}s后重发` : '发送验证码' }}
                    </button>
                </div>

                <button class="login-btn" @click="verifyCode">下一步</button>
            </div>

            <!-- 第三步：重置密码 -->
            <div v-if="step === 3">
                <div class="content">
                    <img :src="require('@/assets/imag1.png')" alt="mima" class="imge">
                    <input type="password" placeholder="请输入新密码" class="input" v-model="newPassword" />
                </div>

                <div class="content">
                    <img :src="require('@/assets/imag1.png')" alt="querenmima" class="imge">
                    <input type="password" placeholder="请确认新密码" class="input" v-model="confirmPassword" />
                </div>

                <button class="login-btn" @click="resetPassword">确认重置</button>
            </div>

            <!-- 错误提示 -->
            <div v-if="errorMessage" class="error-message">
                {{ errorMessage }}
            </div>

            <!-- 成功提示 -->
            <div v-if="successMessage" class="success-message">
                {{ successMessage }}
            </div>
        </div>
    </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { onUnmounted, ref } from 'vue';
import axios from 'axios';

// 路由
const router = useRouter();

// 状态管理
const step = ref(1); // 1:验证手机号 2:验证邮箱和验证码 3:重置密码
const countdown = ref(0);
const timer = ref(null);
const userId = ref(''); // 存储用户ID
const needUpdateEmail = ref(false); // 是否需要更新邮箱

// 表单数据
const phone = ref('');
const email = ref('');
const verificationCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const errorMessage = ref('');
const successMessage = ref('');

// 第一步：验证手机号是否存在
const checkPhone = async () => {
    errorMessage.value = '';
    successMessage.value = '';

    // 验证手机号
    if (!phone.value) {
        errorMessage.value = '请输入手机号';
        return;
    }

    // 简单验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone.value)) {
        errorMessage.value = '请输入有效的手机号';
        return;
    }

    try {
        // 调用后端验证手机号接口
        const response = await axios.post('http://localhost:9001/api/forgot-password/check', {
            phone: phone.value
        });

        if (response.data.exists) {
            // 手机号存在，记录用户ID
            userId.value = response.data.userId;
            // 检查是否需要更新邮箱
            needUpdateEmail.value = !response.data.hasEmail;

            if (needUpdateEmail.value) {
                successMessage.value = '请绑定邮箱以接收验证码';
            } else {
                // 如果已有邮箱，查询该用户的邮箱
                const userResponse = await axios.get(`http://localhost:9001/api/users/${userId.value}`);
                email.value = userResponse.data.email;
                successMessage.value = '手机号验证通过，请获取验证码';
            }

            // 进入第二步
            step.value = 2;
        } else {
            errorMessage.value = response.data.error || '该手机号未注册，请先注册';
        }
    } catch (error) {
        console.error('验证手机号失败:', error);
        errorMessage.value = error.response?.data?.error || '服务器错误，请稍后再试';
    }
};

// 发送验证码
const sendCode = async () => {
    errorMessage.value = '';

    // 检查倒计时
    if (countdown.value > 0) return;

    // 验证邮箱
    if (!email.value) {
        errorMessage.value = '请输入邮箱';
        return;
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email.value)) {
        errorMessage.value = '请输入有效的邮箱地址';
        return;
    }

    try {
        // 如果需要更新邮箱，先更新邮箱
        if (needUpdateEmail.value) {
            await axios.post('http://localhost:9001/api/forgot-password/update-email', {
                userId: userId.value,
                email: email.value
            });
        }

        // 发送验证码
        const response = await axios.post('http://localhost:9001/api/send-email-code', {
            email: email.value
        });

        if (response.status === 200) {
            errorMessage.value = '';
            // 开始倒计时
            countdown.value = 60;
            timer.value = setInterval(() => {
                countdown.value--;
                if (countdown.value <= 0) {
                    clearInterval(timer.value);
                }
            }, 1000);
        }
    } catch (error) {
        console.error('发送验证码失败:', error);
        errorMessage.value = error.response?.data?.error || '发送验证码失败，请重试';
    }
};

// 验证验证码
const verifyCode = async () => {
    errorMessage.value = '';

    if (!verificationCode.value) {
        errorMessage.value = '请输入验证码';
        return;
    }

    // 简单验证验证码格式
    if (verificationCode.value.length !== 6 || !/^\d+$/.test(verificationCode.value)) {
        errorMessage.value = '请输入6位数字验证码';
        return;
    }

    // 进入第三步
    step.value = 3;
};

// 重置密码
const resetPassword = async () => {
    errorMessage.value = '';

    // 表单验证
    if (!newPassword.value) {
        errorMessage.value = '请输入新密码';
        return;
    }

    if (newPassword.value.length < 6) {
        errorMessage.value = '密码长度至少为6位';
        return;
    }

    if (newPassword.value !== confirmPassword.value) {
        errorMessage.value = '两次输入的密码不一致';
        return;
    }

    try {
        // 调用后端重置密码API
        const response = await axios.post('http://localhost:9001/api/forgot-password/reset', {
            phone: phone.value,
            email: email.value,
            code: verificationCode.value,
            newPwd: newPassword.value,
            confirmPwd: confirmPassword.value
        });

        if (response.status === 200) {
            alert('密码重置成功，请使用新密码登录');
            router.push('/Login');
        }
    } catch (error) {
        console.error('重置密码失败:', error);
        errorMessage.value = error.response?.data?.error || '服务器错误，请稍后再试';
    }
};

// 组件卸载时清除定时器
onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value);
    }
});
</script>

<style scoped>
.yemian {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0eff2;
}

.bigbox {
    width: 450px;
    min-height: 550px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
}

.title {
    font-size: 32px;
    color: #d15024;
    margin-bottom: 30px;
}

/* 步骤指示器 */
.steps {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 30px;
    padding: 0 20px;
    box-sizing: border-box;
}

.step {
    font-size: 14px;
    color: #999;
    position: relative;
    padding-bottom: 10px;
}

.step.active {
    color: #ff6200;
    font-weight: bold;
}

.step.completed {
    color: #4CAF50;
}

.step::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #eee;
    transition: all 0.3s;
}

.step.active::after,
.step.completed::after {
    background-color: #ff6200;
}

.content {
    width: 100%;
    height: 50px;
    margin-top: 25px;
    flex-direction: row;
    display: flex;
    align-items: center;
}

.imge {
    margin-left: 6px;
    width: 40px;
    height: 40px;
    background-color: #726e6e7a;
}

.input {
    height: 40px;
    width: 260px;
    border: none;
    outline: none;
    background-color: #726e6e7a;
    padding: 0 10px;
    box-sizing: border-box;
}

.send-code-btn {
    height: 40px;
    background-color: #ff6200;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
    margin-right: 30px;
    padding: 0 15px;
}

.send-code-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

.login-btn {
    font-size: 16px;
    height: 48px;
    margin-left: 30px;
    width: calc(100% - 60px);
    background-color: #ff6200;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 30px;
    transition: background-color 0.3s;
}

.login-btn:hover {
    background-color: #e55a00;
}

.error-message {
    color: red;
    margin-top: 15px;
    font-size: 14px;
    width: calc(100% - 60px);
    text-align: left;
}

.success-message {
    color: #4CAF50;
    margin-top: 15px;
    font-size: 14px;
    width: calc(100% - 60px);
    text-align: left;
}

.hint {
    color: #666;
    font-size: 12px;
    margin-top: 5px;
    margin-left: 80px;
    text-align: left;
    width: calc(100% - 80px);
}

/* 隐藏滚动条（针对webkit浏览器） */
::-webkit-scrollbar {
    display: none !important;
}
</style>